package com.test.personalblogproject.service.impl;

import com.test.personalblogproject.mapper.UserMapper;
import com.test.personalblogproject.pojo.User;
import com.test.personalblogproject.service.UserService;
import com.test.personalblogproject.utils.Md5Util;
import com.test.personalblogproject.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public User findByUserName(String username) {
        User u = userMapper.findByUserName(username);
        return u;
    }

    @Override
    public void register(String username, String password) {
        //加密
        String md5String = Md5Util.getMD5String(password);
        //添加
        userMapper.add(username,md5String);
    }
   // private static final ThreadLocal THREAD_LOCAL = new ThreadLocal();
    @Override
    public void updatePwd(String newPwd) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        String md5String = Md5Util.getMD5String(newPwd);
        userMapper.updatePwd(md5String,id);
    }

    @Override
    public void logout(String  token) {
        redisTemplate.delete(token);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        ops.getOperations().delete(token);
        ThreadLocalUtil.remove();
    }
    @Override
    public void updateNike(User user) {
        String nickname = user.getNickname();
        Integer id = user.getId();
        userMapper.updateNike(id,nickname);
    }
    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updateAvatar(avatarUrl,id);
    }
}
